/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.passport.common.LoginCacheErrTimer;
import com.apache.passport.entity.BlackRoster;
import com.apache.passport.entity.LonErrToken;
import com.apache.passport.entity.UctUser;
import com.apache.passport.manager.BlackRosterManager;
import com.apache.passport.manager.LoginInfoManager;
import com.apache.passport.service.CacheHelper;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * description:
 *
 * @author Hou Dayu 创建时间：2016-1-13
 */
public class CheckPwdPlugin extends SuperPluginConnector  {

//    protected IDao uctUserDao;

    protected IDao blackRosterDao;

    private LoginInfoManager loginInfoManager;

    private BlackRosterManager blackRosterManager;

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

//    public void setUctUserDao(IDao uctUserDao) {
//        this.uctUserDao = uctUserDao;
//    }

    /**
     * TODO 用户密码校验
     *
     * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)
     */
    @Override
    public Object execute(ParamsVo vo) throws Exception {
        ResultEntity result = new ResultEntity();
        result.setResult("true");
        result.setEntity("F");
        result.setMessage("密码不正确");
        String tokenId = (String) vo.getParams("tokenId");
        String sessionId = (String) vo.getParams("sessionId");
        String remoteIp = (String) vo.getParams("remoteIp");
        String synFlag = SystemTools.getInstance().getValue("synFlag");
        ParamsVo<UctUser> vos = vo;
        //登录前首先从数据库中查询下该用户是否存在于黑名单中
        BlackRoster br = (BlackRoster) getBrInfoByIp(vo);
        if (!Validator.isEmpty(br)) {
            LonErrToken token = new LonErrToken();
            token.setLoginCount("12");
            token.setLoginTime(br.getBrCreatetime());
            //2015年1月29日12:58:43  将用户名添加到错误token中
            token.setUserEname(vos.getObj().getUserEname());
            token.setCacheId(remoteIp + br.getBrAccount());
            //存储缓存
            CacheHelper.getInstance().getCache("loginErrToken")
                    .createCacheObject(remoteIp + br.getBrAccount(), token);
            result.setMessage("账户登录12次,已被系统锁定");
            return result;
        }

        //查询用户是否存在
        String userEname = ((UctUser)vo.getObj()).getUserEname();
        UctUser obj = (UctUser) getInfoByEname(userEname);

        //判断用户是否存在
        if (!Validator.isEmpty(obj)) {
            String upass = (String) vo.getParams("userPass");
            //判断密码是否正确
            if ((obj.getUserPass()).equalsIgnoreCase(upass)) {
                //虽然密码正确,但是需要判断下之前缓存中是否存在该用户的登陆错误信息,如果存在,则依然返回等待
                LonErrToken tokenE = (LonErrToken) CacheHelper.getInstance()
                        .getCache("loginErrToken")
                        .getCacheCloneByKey(remoteIp + obj.getUserEname());
                if (!Validator.isEmpty(tokenE)) {
                    String count = tokenE.getLoginCount();
                    int c = Integer.parseInt(count);
                    if ("3".equals(tokenE.getLoginCount()) || "6".equals(tokenE.getLoginCount())
                            || "9".equals(tokenE.getLoginCount()) || c > 12) {
                        //如果错误次数等于以上几个参数,也同样需要校验下时间是否已经过期,防止时间已过,且登录密码正确,却一直没有更新缓存
                        //setErrToken(vo, remoteIp, br, obj);
                        LoginCacheErrTimer.getInstance().setErrToken(vos, remoteIp, br, obj);
                        result.setMessage("信息错误");
                        return result;
                    }
                }
                result.setEntity("T");
                result.setMessage("密码正确");
                //如果登录成功后,清空错误记录缓存
                CacheHelper.getInstance().getCache("loginErrToken")
                        .removeCacheObject(remoteIp + obj.getUserEname());
            } else {
                LoginCacheErrTimer.getInstance().setErrToken(vos, remoteIp, br, obj);
            }
        } else {
            LoginCacheErrTimer.getInstance().setErrToken(vos, remoteIp, br, obj);
        }
        return result;
    }

    /**
     * description:  根据IP及用户名获取黑名单
     *
     * @param vo
     * @return
     */
    public Object getBrInfoByIp(ParamsVo<UctUser> vo) {
        String remoteIp = (String) vo.getParams("remoteIp");
        String userEname = (String) vo.getParams().get("userEname");
        //只验证用户名
        String sql = blackRosterDao.getSql(4);
        if (!Validator.isNull(remoteIp)) {
            sql += " and brIpaddress :=brIpaddress ";
        }
        MethodParam param = new MethodParam("ByIpOrUserEname", "", sql,
                BlackRoster.class.getName());
        param.setParams("brIpaddress", remoteIp);
        param.setParams("brAccount", userEname);
        return blackRosterDao.selectSingle(param);
    }

    public void setLoginInfoManager(LoginInfoManager loginInfoManager) {
        this.loginInfoManager = loginInfoManager;
    }

    public void setBlackRosterDao(IDao blackRosterDao) {
        this.blackRosterDao = blackRosterDao;
    }

    public void setBlackRosterManager(BlackRosterManager blackRosterManager) {
        this.blackRosterManager = blackRosterManager;
    }

}
